package com.ltw.modules.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ltw.modules.common.entity.Result;
import com.ltw.modules.common.entity.SearchBean;
import com.ltw.modules.test.dao.CityDao;
import com.ltw.modules.test.entity.City;
import com.ltw.modules.test.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;

    @Override
    @Transactional
    public Result<City> insertCity(City city) {
        city.setDateCreated(new Date());
        cityDao.insertCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Insert success",city);
    }

    @Override
    @Transactional
    public Result<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Update success",city);
    }

    @Override
    @Transactional
    public Result<Object> deleteCityByCityId(int cityId) {
        cityDao.deleteCityByCityId(cityId);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Delete success",cityId);
    }

    @Override
    public City queryCityByCityId(int cityId) {
        return  cityDao.queryCityByCityId(cityId);
    }

    @Override
    public City queryCityByCityNameAndLocalCityName(String cityName, String localCityName) {
        return cityDao.queryCityByCityNameAndLocalCityName(cityName,localCityName);
    }


/*    @Override
    @Transactional
    public Result<City> insertCity(City city){
        city.setDateCreated(new Date());
        cityDao.insertCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Insert success",city);
    }*/

    @Override
    public PageInfo<City> getCitiesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<>(Optional
                .ofNullable(cityDao.getCitiesBySearchBean(searchBean))
                .orElse(Collections.emptyList()));
    }

    @Override
    public List<City> getCitiesByCountryId(int countryId) {
        return Optional
                .ofNullable(cityDao.getCitiesByCountryId(countryId))
                .orElse(Collections.emptyList());
    }
}
